package com.zxhhyj.music.logic.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.zxhhyj.ffmpeg.tag.MediaTag
import com.zxhhyj.music.logic.bean.SongBean
import com.zxhhyj.music.logic.config.coverFilesDir
import com.zxhhyj.music.logic.repository.SettingRepository
import java.io.File
import java.io.FileOutputStream

fun createSongBean(data: String, id: Long?): SongBean? {
    val songFile = File(data)
    val formatStreamInfo = MediaTag.getMediaFormatStreamInfo(songFile) ?: return null
    val songName =
        (formatStreamInfo.metadata["TITLE"] ?: formatStreamInfo.metadata["title"])?.trim()
            ?: songFile.nameWithoutExtension
    val album = (formatStreamInfo.metadata["ALBUM"] ?: formatStreamInfo.metadata["album"])?.trim()
    val artist =
        (formatStreamInfo.metadata["ARTIST"] ?: formatStreamInfo.metadata["artist"])?.trim()
    val lyric = (formatStreamInfo.metadata["LYRICS"] ?: formatStreamInfo.metadata["lyrics"])?.trim()
        ?: runCatching {
            if (SettingRepository.EnableReadExternalLyrics) {
                File("${songFile.path.substringBeforeLast(".")}.lrc").readText()
            } else {
                null
            }
        }.getOrNull()
    val encoder =
        (formatStreamInfo.metadata["ENCODER"] ?: formatStreamInfo.metadata["encoder"])?.trim()
    val genre = (formatStreamInfo.metadata["GENRE"] ?: formatStreamInfo.metadata["genre"])?.trim()
    val duration = formatStreamInfo.duration.div(1000)
    val bitrate = formatStreamInfo.bitrate.toInt().div(1000)
    val channels = formatStreamInfo.channels
    val sampleRate = formatStreamInfo.sampleRate.toInt()
    val bitDepth = formatStreamInfo.bitsPerRawSample
    val coverFile = formatStreamInfo.cover?.let { coverBytes ->
        BitmapFactory.decodeByteArray(coverBytes, 0, coverBytes.size)?.let { coverBitmap ->
            runCatching {
                val file = File(coverFilesDir, songName)
                FileOutputStream(file).use { fos ->
                    coverBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                }
                file
            }.getOrNull()
        }
    }
    return SongBean(
        coverUrl = coverFile?.path,
        albumName = album,
        artistName = artist,
        duration = duration,
        data = data,
        dateModified = songFile.lastModified(),
        songName = songName,
        size = songFile.length(),
        id = id,
        bitrate = bitrate,
        samplingRate = sampleRate,
        lyric = lyric,
        channels = channels,
        encoder = encoder,
        genre = genre,
        bitDepth = bitDepth
    )
}